<template>
  <div class="fillcontain">
    <el-page-header @back="$router.go(-1)" content="文件查询"> </el-page-header>
    <!-- 搜索框和按钮 -->
    <div class="box">
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="物资编码">
          <el-input v-model="search.code" placeholder="输入物资编码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getData">查询</el-button>
        </el-form-item>
        <el-form-item label="选中文件中的物资编码识别及信息表">
          <el-button type="primary" @click="getData1('view')"> 查看 </el-button>
          <el-button type="success" @click="downloadTable1()"> 下载 </el-button>
        </el-form-item>
        <el-form-item label="选中文件中的物资编码识别结果统计表">
          <el-button type="primary" @click="getData2('view')"> 查看 </el-button>
          <el-button type="success" @click="downloadTable2()"> 下载 </el-button>
        </el-form-item>
        <el-form-item label="选中文件的标注文件">
          <el-button type="success" @click="downloadFile()"> 下载 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 文件表格 -->
    <div class="table_container box">
      <el-table
        ref="table0"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          property="code"
          label="物资编码"
          width="200"
        ></el-table-column>
        <el-table-column
          property="file_name"
          label="文件名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="right_code"
          label="文件编码"
          width="200"
        ></el-table-column>
        <el-table-column
          property="times"
          label="出现次数"
          width="200"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              @click="handelDownload(scope.row)"
              type="text"
              size="small"
              plain
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="Pagination" style="text-align: left; margin-top: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="count"
        ></el-pagination>
      </div>
    </div>

    <!-- 查看选中文件中的物资编码识别及信息表（表一） -->
    <el-dialog
      title="物资编码识别及信息表"
      :visible.sync="dialog1Visible"
      width="90%"
    >
      <el-table id="table1" :data="tableData1" style="width: 100%">
        <el-table-column
          property="fac"
          label="电厂"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_num"
          label="文件编码"
          width="100"
        ></el-table-column>
        <el-table-column
          property="spv"
          label="spv相关"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_name"
          label="文件名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="file_size"
          label="文件大小"
          width="100"
        ></el-table-column>
        <el-table-column
          property="code"
          label="物资编码"
          width="120"
        ></el-table-column>
        <el-table-column
          property="state"
          label="识别状态分类"
          width="100"
        ></el-table-column>
        <el-table-column
          property="factory_state"
          label="物料状态（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="group_state"
          label="物料状态（集团级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="cpn_level"
          label="备件分级"
          width="100"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog1Visible = false"> 取 消 </el-button>
        <el-button type="success" @click="downloadTable1()"> 下 载 </el-button>
      </div>
    </el-dialog>

    <!-- 查看选中文件中的物资编码识别结果统计表（表二） -->
    <el-dialog
      title="物资编码识别结果统计表"
      :visible.sync="dialog2Visible"
      width="90%"
    >
      <el-table id="table2" :data="tableData2" style="width: 100%">
        <el-table-column
          property="fac"
          label="电厂"
          width="100"
        ></el-table-column>
        <el-table-column
          property="file_num"
          label="文件编码"
          width="100"
        ></el-table-column>
        <el-table-column
          property="spv"
          label="spv相关"
          width="80"
        ></el-table-column>
        <el-table-column
          property="file_name"
          label="文件名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="file_size"
          label="文件大小"
          width="100"
        ></el-table-column>
        <el-table-column
          :formatter="codeNum"
          label="提取编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="right_num"
          label="现有编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="fault_num"
          label="失效编码数"
          width="100"
        ></el-table-column>
        <el-table-column
          property="fault_per"
          label="失效占比"
          width="100"
        ></el-table-column>
        <!-- <el-table-column
          property="rec_num"
          label="推荐编码数"
          width="100"
        ></el-table-column> -->
        <el-table-column
          property="facAF_num"
          label="全部冻结（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="facFB_num"
          label="冻结采购（工厂级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="gpAF_num"
          label="全部冻结（集团级）"
          width="100"
        ></el-table-column>
        <el-table-column
          property="gpFB_num"
          label="冻结采购（集团级）"
          width="100"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog2Visible = false">取 消</el-button>
        <el-button type="success" @click="downloadTable2()"> 下 载 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import XLSX from "xlsx";
import {
  getResAnalysis,
  getOneFileAnalysis,
  getOneFileResult,
  createTable1,
  createTable2,
  getHighlightUrl,
} from "../api/getData";

export default {
  data() {
    return {
      search: {
        code: "",
      },
      tableData: [],
      tableData1: [
        {
          a: "GF1",
          b: "GF1-GRE-TPMAPI-0005",
          c: "否",
          file_name: "**",
          fileSize: "**",
          code: "9000079008",
          state: "吻合",
          e: "",
          factory_state: "冻结采购",
          group_state: "全部冻结",
          cpn_level: "一般备件",
        },
        {
          a: "GF1",
          b: "GF1-GRE-TPMAPI-0005",
          c: "否",
          file_name: "**",
          fileSize: "**",
          code: "9000079012",
          state: "疑似",
          e: "351200051",
          factory_state: "N/A",
          group_state: "N/A",
          cpn_level: "重要备件",
        },
      ],
      tableData2: [
        {
          factory: "GF1",
          codeSet: "GF1-GRE-TPMAPI-0005",
          spv: "否",
          fileName: "**",
          file_size: "**",
          right_num: "10",
          fault_num: "1",
          fault_per: "10%",
          rec_num: "1",
          facAF_num: "6",
          facFB_num: "4",
          gpAF_num: "0",
          gpFB_num: "0",
        },
      ],
      selection: [], // 选中的数据
      selectionAll: [], // 选中全部的数据
      dialogVisible: false,
      dialog1Visible: false,
      dialog2Visible: false,
      dialog3Visible: false,
      currentRow: 10,
      offset: 0,
      limit: 10,
      count: 0,
      currentPage: 1,
    };
  },
  components: {},
  created() {
    // this.initData();
  },
  methods: {
    // 获取表格数据
    async getData() {
      if (this.search.code) {
        try {
          const data = await getResAnalysis(this.search.code);

          if (data.success) {
            // 数组合并
            let list = [];
            for (let i = 0; i < data.list.length; i++) {
              list = list.concat(data.list[i]);
              console.log(list);
            }
            console.log("表格数据", list);
            this.tableData = list;
            this.selectionAll = list.map((item) => item.file_name);
            this.count = list.length;
          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
        }
      } else {
        this.$message.error("请输入物资编码");
      }
    },
    // 获取并查看表格1的数据
    async getData1(action) {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取表一的数据
          const data = await getOneFileResult(this.selection);

          if (data.success) {
            // 数组合并
            let list = [];
            for (let i = 0; i < data.list.length; i++) {
              list = list.concat(data.list[i]);
              console.log(list);
            }
            console.log("表一", list);

            this.tableData1 = list;

            // 显示表一对话框
            if (action === "view") {
              this.dialog1Visible = true;
            }
            //下载表一
            if (action === "download") {
              // // 表一的thead
              // const thead = document.querySelectorAll("table")[2].tHead;
              // // 表一的包含tbody的table
              // let table = document.querySelectorAll("table")[3];
              // // 向表一的table中添加表头
              // table.tHead = thead;
              const table1 = document.querySelector(
                "#table1 div.el-table__body-wrapper table"
              );
              console.log(table1);
              // 生成表格
              const wb = XLSX.utils.table_to_book(table1, { sheet: "sheet 1" });
              // 下载表格
              XLSX.writeFile(wb, "物资编码识别及信息表.xlsx");
            }
          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 获取并查看表格2的数据
    async getData2(action) {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取表2的数据
          const data = await getOneFileAnalysis(this.selection);

          if (data.success) {
            // 数组合并
            // let list = [];
            // for (let i = 0; i < data.list.length; i++) {
            //   list = list.concat(data.list[i]);
            //   console.log(list);
            // }
            // console.log("表二", list);
            let list = data.list;
            // 计算疑似比率并插入
            list = list.map((item) => {
              let totalNum = item.fault_num + item.right_num;
              let FaultRate =
                ((item.fault_num / totalNum) * 100).toFixed(2) + "%";
              item.fault_per = totalNum ? FaultRate : 0;
              return item;
            });
            this.tableData2 = list;

            // 显示表二对话框
            if (action === "view") {
              this.dialog2Visible = true;
            }
            //下载表二
            if (action === "download") {
              // // 表二的thead
              // const thead = document.querySelectorAll("table")[4].tHead;
              // // 表二的包含tbody的table
              // let table = document.querySelectorAll("table")[5];
              // // 向表二的table中添加表头
              // table.tHead = thead;
              // console.log(table);
              const table2 = document.querySelector(
                "#table2 div.el-table__body-wrapper table"
              );

              // 生成表格
              const wb = XLSX.utils.table_to_book(table2, { sheet: "sheet 1" });
              // 下载表格
              XLSX.writeFile(wb, "物资编码识别及信息表.xlsx");
            }
          } else {
            throw new Error("获取数据失败");
          }
        } catch (err) {
          console.log("获取数据失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 下载表格1
    async downloadTable1(action) {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取表一的数据
          const data = await createTable1(this.selection);

          if (data.success) {
            window.open(data.url);
          } else {
            throw new Error("下载表格1失败");
          }
        } catch (err) {
          console.log("下载表格1失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 下载表格2
    async downloadTable2(action) {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取表一的数据
          const data = await createTable2(this.selection);

          if (data.success) {
            window.open(data.url);
          } else {
            throw new Error("下载表格2失败");
          }
        } catch (err) {
          console.log("下载表格1失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 下载标注文件
    async downloadFile(action) {
      // 判断是否选中文件
      if (this.selection.length) {
        try {
          // 获取标注文件
          const data = await getHighlightUrl(this.selection);

          if (data.success) {
            for (const i in data.list) {
              if (data.list[i]) {
                window.open(data.list[i]);
              }
            }
          } else {
            throw new Error("下载标注文件失败");
          }
        } catch (err) {
          console.log("下载标注文件失败", err);
        }
      } else {
        this.$message.error("请选择文件");
      }
    },
    // 选中状态改变
    handleSelectionChange(val) {
      console.log("选中的数据", val);
      this.selection = val.map((item) => item.file_name);
      console.log(this.selection);
    },
    // 下载操作
    handelDownload(row) {
      this.$message.error("敬请期待");
      console.log(row);
    },
    // 页面显示数据数改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    // 页面改变重新获取数据
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      // this.getUsers()
    },
    // 计算提取编码数
    codeNum(row, column) {
      return row.right_num + row.fault_num;
    },
  },
};
</script>

<style lang="less">
// @import url("../style/mixin.less");
@import url("../assets/css/main.less");
.table_container {
  padding: 20px;
}
.box {
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  .el-form-item {
    margin: 20px 20px 0 0;
  }
}
</style>
